package jnpf.permission.util.implicit;

import jnpf.config.JnpfOauthConfig;
import jnpf.constant.MsgCode;
import jnpf.exception.LoginException;
import jnpf.permission.util.implicit.request.ImplicitDingTalkRequest;
import jnpf.permission.util.implicit.request.ImplicitQywxRequest;
import jnpf.permission.util.socials.AuthCallbackNew;
import jnpf.permission.util.socials.SocialsConfig;
import jnpf.util.StringUtil;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.enums.AuthResponseStatus;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;

/**
 * 免登工具类
 *
 * @author JNPF开发平台组
 * @version v5.0.0
 * @copyright 引迈信息技术有限公司
 * @date 2024/5/23 11:09:26
 */
@Component
public class ImplicitLoginUtil {
    @Autowired
    private SocialsConfig socialsConfig;
    @Autowired
    private JnpfOauthConfig oauthConfig;

    public String getAuthLink(String source) {
        ImplicitLoginRequest authRequest = this.getAuthRequest(source, null, null);
        return authRequest.getAuthLoginLink();
    }

    public String loginByCode(String source, String code, String state) {
        //获取第三方请求
        AuthCallbackNew callback = new AuthCallbackNew();
        callback.setAuthCode(code);
        callback.setAuth_code(code);
        callback.setAuthorization_code(code);
        callback.setCode(code);
        callback.setState(state);
        ImplicitLoginRequest authRequest = this.getAuthRequest(source, null, null);
        AuthResponse<AuthUser> res = authRequest.getUserId(callback);
        if (AuthResponseStatus.FAILURE.getCode() == res.getCode()) {
            throw new LoginException("连接失败！");
        } else if (AuthResponseStatus.SUCCESS.getCode() != res.getCode()) {
            throw new LoginException("授权失败:" + res.getMsg());
        }
        //登录用户第三方id
        return getSocialUuid(res);
    }

    private String getSocialUuid(AuthResponse<AuthUser> res) {
        String uuid = res.getData().getUuid();
        if (res.getData().getToken() != null && StringUtil.isNotEmpty(res.getData().getToken().getUnionId())) {
            uuid = res.getData().getToken().getUnionId();
        }
        return uuid;
    }

    /**
     * 根据配置信息获取请求对象
     *
     * @param
     * @return
     * @copyright 引迈信息技术有限公司
     * @date 2022/7/21
     */
    public ImplicitLoginRequest getAuthRequest(String source, String userId, String tenantId) {
        ImplicitLoginRequest authRequest = null;
        String url = oauthConfig.getJnpfDomain() + "/api/oauth/Login/implicit";
        SocialsConfig.Config socialConfig;
        switch (source.toLowerCase()) {
            case "dingtalk":
                socialConfig = socialsConfig.getSocialMap().get("dingtalk");
                authRequest = new ImplicitDingTalkRequest(AuthConfig.builder()
                        .clientId(socialConfig.getClientId())
                        .clientSecret(socialConfig.getClientSecret())
                        .redirectUri(URLEncoder.encode(url))
                        .build());
                break;
            case "wechat_enterprise":
                socialConfig = socialsConfig.getSocialMap().get("wechat_enterprise");
                authRequest = new ImplicitQywxRequest(AuthConfig.builder()
                        .clientId(socialConfig.getClientId())
                        .clientSecret(socialConfig.getClientSecret())
                        .redirectUri(URLEncoder.encode(url))
                        .agentId(socialConfig.getAgentId())
                        .build());
                break;
            default:
                break;
        }
        if (null == authRequest) {
            throw new AuthException(MsgCode.OA024.get());
        }
        return authRequest;
    }
}
